package com.ssy.lingxi.system.handler.converter;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
import java.util.HashMap;

/**
 * PostgreSQL jsonb类型字段转换为Map<String, Object>类型的转换器
 * @author 万宁
 * @version 2.0.0
 * @date 2021-01-14
 */
@Converter(autoApply = true)
public class JpaJsonToMapConverter implements AttributeConverter<HashMap<String, Object>, String> {
    private final static ObjectMapper OBJECT_MAPPER = new ObjectMapper();

    @Override
    public String convertToDatabaseColumn(HashMap<String, Object> attribute) {
        try {
            return OBJECT_MAPPER.writeValueAsString(attribute);
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    @Override
    public HashMap<String, Object> convertToEntityAttribute(String dbData) {
        try {
            if(dbData == null) {
                return new HashMap<>();
            }

            return OBJECT_MAPPER.readValue(dbData, new TypeReference<HashMap<String, Object>>() {});
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
